//
//  SkySimCardBaseData.m
//  BlueDemo
//
//  Created by wulanzhou on 16/3/14.
//  Copyright © 2016年 wulanzhou. All rights reserved.
//

#import "SkySimCardData.h"

@implementation SkySimCardData

/**
 *  蓝牙解码处理
 *
 *  @param characteristicValue 需要解码的数据
 *
 *  @return
 */
+ (id)decodeSkySimCardWithData:(NSData *)characteristicValue{
    
    if (characteristicValue&&[characteristicValue length]>0) {
        
        Byte *b=(Byte *)[characteristicValue bytes];
        if (b[0]!=0x81) {
            return nil;
        }
        
        int len=0;
        if (b[1]) {
            len=b[1]&0xff;
        }
        
        if (len>0) {
            NSData *subData=[characteristicValue subdataWithRange:NSMakeRange(characteristicValue.length-len, len)];
            b=(Byte *)[subData bytes];
            if (b[0]&&b[0]!=0x81) {
                return nil;
            }
        }
        
        
        return [[self alloc] initWithData:characteristicValue];
        
    }
    return nil;
}

/**
 *  解码处理
 *
 *  @param characteristicValue 需要解码的数据
 *
 *  @return
 */
- (id)initWithData:(NSData *)characteristicValue{
    
    if (self=[super init]) {
        
        Byte *b=(Byte *)[characteristicValue bytes];
        
        self.headCmd=b[0];
        self.contentLen=b[1]&0xff;
        
        characteristicValue=[characteristicValue subdataWithRange:NSMakeRange(characteristicValue.length-self.contentLen, self.contentLen)];
        b=(Byte *)[characteristicValue bytes];
        
        self.bodyCmd=b[1];
        self.bodyLen=b[2]&0xff;

        if (self.bodyLen>0) {
            self.bodyData=[characteristicValue subdataWithRange:NSMakeRange(characteristicValue.length-self.bodyLen, self.bodyLen)];
        }
        
        
    }
    
    return self;
}

/**
 *  蓝牙编码处理
 *
 *  @return
 */
- (NSData *)encodeSkySimCardData{
    
    return [self separateDataPackHandler];
}

- (NSString *)bodyDataToHexString{
    
    if (self.bodyData&&[self.bodyData length]>0) {
        
        Byte *subByte=(Byte *)[self.bodyData bytes];
        
        NSMutableString * hexString = [[NSMutableString alloc] init];
        
        for(NSUInteger i = 0; i < self.bodyData.length; i++ )
            [hexString appendString:[NSString stringWithFormat:@"%0.2hhx", subByte[i]]];
        
        return hexString;
        
    }
    
    return @"";
}

#pragma mark -私有方法
/**
 *  获取所有分包数据
 *
 *  @return
 */
- (NSData *)separateDataPackHandler{
    
    NSInteger ble_max_len=15;//第一段数据最多15个字节
    
    //计算分段的总数
    NSInteger total_len=1;
    NSInteger dataLen=self.bodyData.length-ble_max_len;
    if (dataLen>0) {
        total_len+=dataLen/18;
        if (dataLen%18!=0) {
            total_len++;
        }
    }
    
    //总的数据包长头
    NSInteger headLen=(0x80&0xff)+total_len;
    Byte headByte[1];
    headByte[0]=headLen&0xff;
    NSData *headDataPack=[[NSData alloc] initWithBytes:headByte length:sizeof(headByte)];
    
    
    NSMutableData *mulData=[NSMutableData dataWithCapacity:1024];
    
    NSInteger _currentIndex=0;
    NSString *rangeStr=nil;
    NSData *subData=nil;
    
    for (NSInteger i=1; i<total_len+1; i++) {
        
        // 预加 最大包长度，如果依然小于总数据长度，可以取最大包数据大小
        if ((_currentIndex + ble_max_len) < [self.bodyData length]) {
            rangeStr = [NSString stringWithFormat:@"%li,%li", (long)_currentIndex, (long)ble_max_len];
            subData = [self.bodyData subdataWithRange:NSRangeFromString(rangeStr)];
            _currentIndex += ble_max_len;
            
            //添加数据
            [mulData appendData:[self addHeadDataPack:headDataPack subDataPack:subData dataPackIndex:i]];
        }
        else {
            rangeStr = [NSString stringWithFormat:@"%li,%i", (long)_currentIndex, (int)([self.bodyData length] - _currentIndex)];
            subData = [self.bodyData subdataWithRange:NSRangeFromString(rangeStr)];
            _currentIndex += ble_max_len;
            
            //添加数据
            [mulData appendData:[self addHeadDataPack:headDataPack subDataPack:subData dataPackIndex:i]];
        }
        
        if (i==1) {
            ble_max_len+=3;
        }
    }
    
    return mulData;
}

/**
 *  返回一个数据包
 *
 *  规则如下：
 *  第一段数据包为:8x(x表示总的数据包长度)+长度(81之后的长度)+81+指令码+长度(总的发送数据长度)+数据(总数据或分段数据)
 *  第二段数据包为:序号(从01开始)+长度(分段数据长度)+分段数据
 *  以此类推
 *
 *  @param headDataPack 总数据包头
 *  @param dataPack     分段数据
 *  @param packIndex    第几个数据包
 *
 *  @return
 */
- (NSData *)addHeadDataPack:(NSData *)headDataPack subDataPack:(NSData *)dataPack dataPackIndex:(NSInteger)packIndex{
    
    NSMutableData *mulData=[NSMutableData dataWithCapacity:1024];
    
    
    if (packIndex==1) {
        //总数据包
        [mulData appendData:headDataPack];
        
        
        NSMutableData *subData=[NSMutableData dataWithCapacity:1024];
        
        //第几个数据包8x
        Byte b[1];
        b[0]=0x81;
        [subData appendBytes:b length:sizeof(b)];
        
        //指令码
        b[0]=self.bodyCmd;
        [subData appendBytes:b length:sizeof(b)];
        
        //长度
        b[0]=self.bodyData.length&0xff;
        [subData appendBytes:b length:sizeof(b)];
        
        //数据
        [subData appendData:dataPack];
        
        //总数据包长度
        b[0]=subData.length&0xff;
        [mulData appendBytes:b length:sizeof(b)];
        
        [mulData appendData:subData];
        
        
    }else{
        Byte b[1];
        //序号
        b[0]=(packIndex-1)&0xff;
        [mulData appendBytes:b length:sizeof(b)];
        
        //数据长度
        b[0]=dataPack.length&0xff;
        [mulData appendBytes:b length:sizeof(b)];
        
        //分段数据
        [mulData appendData:dataPack];
    }
    [self writeLogWithData:mulData];
    return mulData;
}

/**
 *  输出16进制内容
 *
 *  @param data 要输出的数据
 */
- (void)writeLogWithData:(NSData *)data{
    
    Byte *bufBytes=(Byte *)[data bytes];
    NSMutableString * hexString = [[NSMutableString alloc] init];
    for(NSUInteger i = 0; i <data.length; i++ )
        [hexString appendString:[NSString stringWithFormat:@"%0.2hhx", bufBytes[i]]];
    
    
    NSString *cmdName=@"";
    if ([NSStringFromClass([self class]) isEqualToString:@"SkyCmdSearchCardData"]) {
        cmdName=@"查询";
    }else if ([NSStringFromClass([self class]) isEqualToString:@"SkyCmdChangeCard"]){
        cmdName=@"激活";
    }else if ([NSStringFromClass([self class]) isEqualToString:@"SkyCmdDownloadCardData"]){
        cmdName=@"下载分段";
    }else if ([NSStringFromClass([self class]) isEqualToString:@"SkyCmdGetCardID"]){
        cmdName=@"取得cardid";
    }else if ([NSStringFromClass([self class]) isEqualToString:@"SkyCmdHeartBeat"]){
        cmdName=@"心跳";
    }else if ([NSStringFromClass([self class]) isEqualToString:@"SkyCmdReleaseCard"]){
        cmdName=@"释放";
    }
    
    NSLog(@"%@指令 =%@",cmdName,hexString);
    
}

@end
